package com.summerbird.mallchat.common.common.service;

import com.summerbird.mallchat.common.common.exception.BusinessException;
import com.summerbird.mallchat.common.common.exception.CommonErrorEnum;
import com.summerbird.mallchat.common.common.utils.AssertUtil;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

@Service
public class LockService {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 排队等待
     * @param key
     * @param waitTime
     * @param unit
     * @param supplier
     * @return
     * @param <T>
     */
    @SneakyThrows
    public <T> T executeWithLockThrows(String key, long waitTime, TimeUnit unit, SupplierThrow<T> supplier){
        RLock lock = redissonClient.getLock(key);
        boolean b = lock.tryLock(waitTime, unit);
        if(!b){
            throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
        }
        try {
            return supplier.get();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 立刻执行，无需等待
     * 有返回值
     * @param key
     * @param supplier
     * @return
     * @param <T>
     */
    public <T> T executeWithLock(String key, Supplier<T> supplier){
        return this.executeWithLockThrows(key, -1, TimeUnit.MILLISECONDS, supplier::get);
    }

    /**
     * 立刻执行，无需等待
     * @param key
     * @param runnable
     * @return
     * @param <T>
     */
    public <T> T executeWithLock(String key, Runnable runnable){
        return this.executeWithLockThrows(key, -1, TimeUnit.MILLISECONDS, ()->{
            runnable.run();
            return null;
        });
    }

    @FunctionalInterface
    public interface SupplierThrow<T> {

        /**
         * Gets a result.
         *
         * @return a result
         */
        T get() throws Throwable;
    }
}
